// DOM 元素
const chatForm = document.getElementById('chatForm');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const messagesContainer = document.getElementById('messagesContainer');
const newChatBtn = document.getElementById('newChatBtn');
const chatContainer = document.getElementById('chatContainer');

// 聊天状态
let config = null;
let currentPage = null;
let currentApiConfig = null;
let currentSystemPrompt = null;
let messages = [];
let controller = null;
let isStreaming = false;

// 加载配置和聊天历史
async function initialize() {
  try {
    const response = await fetch('config.json');
    config = await response.json();
    
    // 确定当前页面
    const path = window.location.pathname;
    currentPage = path.substring(path.lastIndexOf('/') + 1);
    
    // 如果没有找到特定页面配置，默认使用 chat.html 配置
    const pageConfig = config.page_config[currentPage] || config.page_config['chat.html'];
    
    // 根据页面默认设置 API 配置
    const apiProvider = pageConfig.default_api;
    currentApiConfig = config.api_config[apiProvider];
    
    // 根据页面默认设置系统提示
    const promptKey = pageConfig.default_prompt;
    currentSystemPrompt = config.system_prompts[promptKey];
    
    console.log(`使用 API: ${apiProvider}, 提示: ${promptKey}`);
    
    // 如果可用，从 localStorage 加载聊天历史
    const chatKey = `chatMessages_${currentPage}`;
    const savedMessages = localStorage.getItem(chatKey);
    if (savedMessages) {
      messages = JSON.parse(savedMessages);
      renderMessages();
    } else {
      // 添加初始系统消息和选定的提示
      if (currentSystemPrompt) {
        // 添加初始问候语
        addAIMessage('你好！我是 AI 助手。今天我能帮你什么忙？');
      }
    }
  } catch (error) {
    console.error('初始化聊天时出错:', error);
    addSystemMessage('加载配置时出错。请检查您的 config.json 文件。');
  }
}

// 渲染所有消息
function renderMessages() {
  messagesContainer.innerHTML = '';
  
  messages.forEach(message => {
    if (message.role === 'user') {
      addUserMessageElement(message.content);
    } else if (message.role === 'assistant') {
      addAIMessageElement(message.content);
    }
  });
  
  // 滚动到底部
  chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 添加用户消息
function addUserMessage(content) {
  const message = { role: 'user', content };
  messages.push(message);
  saveMessages();
  addUserMessageElement(content);
}

// 为用户添加消息元素
function addUserMessageElement(content) {
  const messageElement = document.createElement('div');
  messageElement.className = 'flex items-start justify-end message-animation';
  
  const timestamp = new Date();
  const timeString = `${timestamp.getHours().toString().padStart(2, '0')}:${timestamp.getMinutes().toString().padStart(2, '0')}`;
  
  messageElement.innerHTML = `
    <div class="flex flex-col max-w-[75%]">
      <div class="bg-blue-600 rounded-2xl p-4 text-white shadow-md">
        <p>${escapeHtml(content)}</p>
      </div>
      <div class="text-xs text-gray-500 mt-1 text-right mr-1">${timeString}</div>
    </div>
    <div class="flex-shrink-0 ml-3">
      <div class="w-10 h-10 rounded-full bg-green-500 flex items-center justify-center text-white shadow-md">
        我
      </div>
    </div>
  `;
  
  messagesContainer.appendChild(messageElement);
  chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 添加 AI 消息
function addAIMessage(content) {
  const message = { role: 'assistant', content };
  messages.push(message);
  saveMessages();
  addAIMessageElement(content);
}

// 为 AI 添加消息元素
function addAIMessageElement(content) {
  const messageElement = document.createElement('div');
  messageElement.className = 'flex items-start message-animation';
  
  const timestamp = new Date();
  const timeString = `${timestamp.getHours().toString().padStart(2, '0')}:${timestamp.getMinutes().toString().padStart(2, '0')}`;
  
  // 如果可用，使用 marked 渲染 markdown
  let renderedContent = content;
  if (typeof marked !== 'undefined') {
    renderedContent = marked.parse(content);
  } else {
    renderedContent = escapeHtml(content);
  }
  
  messageElement.innerHTML = `
    <div class="flex-shrink-0 mr-3">
      <div class="w-10 h-10 rounded-full bg-purple-600 flex items-center justify-center text-white shadow-md">
        <span class="font-bold">AI</span>
      </div>
    </div>
    <div class="flex flex-col max-w-[75%]">
      <div class="bg-purple-100 rounded-2xl p-4 text-gray-800 shadow-sm markdown-body">
        ${renderedContent}
      </div>
      <div class="text-xs text-gray-500 mt-1 ml-1">${timeString}</div>
    </div>
  `;
  
  messagesContainer.appendChild(messageElement);
  
  // 如果 hljs 可用，应用语法高亮
  if (typeof hljs !== 'undefined') {
    messageElement.querySelectorAll('pre code').forEach((block) => {
      hljs.highlightBlock(block);
    });
  }
  
  chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 在 AI 正在输入时添加临时消息
function addTypingIndicator() {
  const typingElement = document.createElement('div');
  typingElement.id = 'typingIndicator';
  typingElement.className = 'flex items-start message-animation';
  typingElement.innerHTML = `
    <div class="flex-shrink-0 mr-3">
      <div class="w-10 h-10 rounded-full bg-purple-600 flex items-center justify-center text-white shadow-md">
        <span class="font-bold">AI</span>
      </div>
    </div>
    <div class="flex flex-col max-w-[75%]">
      <div class="bg-purple-100 rounded-2xl p-4 text-gray-800 shadow-sm">
        <p class="typing-indicator">思考中</p>
      </div>
    </div>
  `;
  messagesContainer.appendChild(typingElement);
  chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 移除输入指示器
function removeTypingIndicator() {
  const typingElement = document.getElementById('typingIndicator');
  if (typingElement) {
    typingElement.remove();
  }
}

// 使用部分响应更新输入指示器
function updateTypingIndicator(content) {
  const typingElement = document.getElementById('typingIndicator');
  if (typingElement) {
    // 如果可用，使用 marked 渲染 markdown
    if (typeof marked !== 'undefined') {
      typingElement.querySelector('div.bg-purple-100').innerHTML = `<div class="markdown-body">${marked.parse(content)}</div>`;
      
      // 如果 hljs 可用，应用语法高亮
      if (typeof hljs !== 'undefined') {
        typingElement.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightBlock(block);
        });
      }
    } else {
      typingElement.querySelector('p').textContent = content;
    }
  }
}

// 添加系统消息（用于错误等）
function addSystemMessage(content) {
  const messageElement = document.createElement('div');
  messageElement.className = 'flex items-start justify-center my-2';
  messageElement.innerHTML = `
    <div class="bg-red-100 rounded-lg p-2 max-w-[80%]">
      <p class="text-red-800 text-sm">${escapeHtml(content)}</p>
    </div>
  `;
  messagesContainer.appendChild(messageElement);
  chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 将消息保存到 localStorage
function saveMessages() {
  const chatKey = `chatMessages_${currentPage}`;
  localStorage.setItem(chatKey, JSON.stringify(messages));
}

// 转义 HTML 以防止 XSS
function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

// 向 API 发送消息
async function sendMessageToAI(userMessage) {
  if (!config || !currentApiConfig || !currentApiConfig.api_key) {
    addSystemMessage('未找到 API 配置或密钥。请检查您的 config.json 文件。');
    return;
  }

  addTypingIndicator();
  isStreaming = true;
  updateSendButton();

  // 为 API 准备消息
  const apiMessages = [];
  
  // 如果可用，添加系统消息
  if (currentSystemPrompt && currentSystemPrompt.content) {
    apiMessages.push({
      role: 'system',
      content: currentSystemPrompt.content
    });
  }
  
  // 添加对话历史
  messages.forEach(msg => {
    apiMessages.push({
      role: msg.role,
      content: msg.content
    });
  });

  try {
    controller = new AbortController();
    const signal = controller.signal;

    const response = await fetch(currentApiConfig.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${currentApiConfig.api_key}`
      },
      body: JSON.stringify({
        model: currentApiConfig.model,
        messages: apiMessages,
        stream: true
      }),
      signal
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error?.message || '未知错误');
    }

    const reader = response.body.getReader();
    let aiResponse = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      // 将块转换为文本
      const chunk = new TextDecoder().decode(value);
      
      // 处理 SSE 格式
      const lines = chunk.split('\n');
      for (const line of lines) {
        if (line.startsWith('data: ') && line !== 'data: [DONE]') {
          try {
            const data = JSON.parse(line.substring(6));
            if (data.choices && data.choices[0]?.delta?.content) {
              const content = data.choices[0].delta.content;
              aiResponse += content;
              
              // 使用当前响应更新输入指示器
              updateTypingIndicator(aiResponse);
              chatContainer.scrollTop = chatContainer.scrollHeight;
            }
          } catch (e) {
            console.error('解析 SSE 数据时出错:', e);
          }
        }
      }
    }

    // 添加完整的 AI 响应
    removeTypingIndicator();
    if (aiResponse.trim()) {
      addAIMessage(aiResponse);
    }
  } catch (error) {
    if (error.name === 'AbortError') {
      console.log('请求已中止');
    } else {
      console.error('向 AI 发送消息时出错:', error);
      addSystemMessage(`错误: ${error.message}`);
    }
    removeTypingIndicator();
  } finally {
    isStreaming = false;
    controller = null;
    updateSendButton();
  }
}

// 更新发送按钮状态和文本
function updateSendButton() {
  if (isStreaming) {
    sendButton.textContent = '停止';
    sendButton.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
      </svg>
      停止
    `;
    sendButton.classList.remove('bg-blue-600', 'hover:bg-blue-700');
    sendButton.classList.add('bg-red-500', 'hover:bg-red-600');
  } else {
    sendButton.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
      </svg>
      发送
    `;
    sendButton.classList.remove('bg-red-500', 'hover:bg-red-600');
    sendButton.classList.add('bg-blue-600', 'hover:bg-blue-700');
  }
}

// 事件监听器
chatForm.addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const message = messageInput.value.trim();
  
  if (isStreaming) {
    // 如果当前正在流式传输，中止请求
    if (controller) {
      controller.abort();
    }
    return;
  }
  
  if (message) {
    messageInput.value = '';
    addUserMessage(message);
    await sendMessageToAI(message);
  }
});

// 添加键盘快捷键（Ctrl+Enter 或 Command+Enter）发送消息
messageInput.addEventListener('keydown', (e) => {
  if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
    chatForm.dispatchEvent(new Event('submit'));
  }
});

newChatBtn.addEventListener('click', () => {
  if (confirm('开始新的对话？这将清除当前的对话内容。')) {
    messages = [];
    const chatKey = `chatMessages_${currentPage}`;
    localStorage.removeItem(chatKey);
    renderMessages();
    
    // 添加初始问候语
    addAIMessage('你好！我是 AI 助手。今天我能帮你什么忙？');
  }
});

// 初始化聊天
initialize();